﻿using BySoft.Server.Business;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.MasteData
{
    public partial class ProductEdit : AuthBasePage
    {
        public string sequenceName
        {
            get { return "MD_Product"; }
        }


        private string m_strTbl = "MD_Product";
        private string m_strMainKey = "ProductID";

        #region   read data 
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void InitEditData()
        {
            string strCode = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
            GetProductById(strCode);
            InitDtDUpFile();
            InitDtTechFile();
        }

        private void GetProductById(string strCode)
        {
            if (!string.IsNullOrEmpty(strCode))
            {
                MdProductEntity product = MdProduct.GetMdProductByID(strCode);
                if (product != null)
                {
                    this.lblProductID.Text = product.ProductID.Trim();
                    this.txtProductName.Text = product.ProductName.Trim();
                    this.txtUnit.Text = product.Unit.Trim();
                    this.txtSpecifications.Text = product.Specifications.Trim();
                    this.txtSafeStock.Text = product.SafeStock.ToString();
                    this.ddlProductType.SelectedValue = product.ProductTypeID.Trim();
                    this.txtOutSide.Text= product.OutSide.ToString();
                    this.txtInSide.Text = product.InSide.ToString();
                }



            }
        }

        //read map file
        private void InitDtDUpFile()
        {

            string ProductID = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
            if (!string.IsNullOrEmpty(ProductID))
            {

                DataTable dTable = DtDUpFile.Copy();
                InitAttachmentFileDt(ProductID, dTable, "ProductMap");
                DtDUpFile = dTable.Copy();

                BindMapFileData();
            }
        }

        //read tech file
        private void InitDtTechFile()
        {

            string ProductID = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
            if (!string.IsNullOrEmpty(ProductID))
            {

                DataTable dTable = DtTechFile.Copy();
                InitAttachmentFileDt(ProductID, dTable, "ProductTech");
                DtTechFile = dTable.Copy();

                BindTechFileData();
            }
        }

        private  DataTable InitAttachmentFileDt(string ProductID, DataTable dTable, string strFormType)
        {
            DataTable dt = MdAttachment.GetMdAttachment(ProductID, strFormType);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow d = dTable.NewRow();
                    d["AttachmentID"] = CommonMethod.GetString(dr["AttachmentID"]);
                    d["FileType"] = CommonMethod.GetString(dr["FileType"]);
                    d["FileSize"] = CommonMethod.GetString(dr["FileSize"]);
                    d["UpDateTime"] = CommonMethod.GetString(dr["UpDateTime"]);
                    d["FileURL"] = CommonMethod.GetString(dr["FileURL"]);
                    d["FileName"] = CommonMethod.GetString(dr["FileName"]);
                    d["FormType"] = CommonMethod.GetString(dr["FormType"]);
                    d["FormID"] = CommonMethod.GetString(dr["FormID"]);
                    d["Status"] = CommonMethod.GetString(dr["Status"]);
                    d["AttachmentID"] = CommonMethod.GetString(dr["AttachmentID"]);
                    string path = "/UpFile/";
                    path += strFormType + "/" + d["FileURL"];
                    path = Request.Url.Scheme + "://" + Request.Url.Authority + path;
                    d["OpenURL"] = path;
                    dTable.Rows.Add(d);
                }
            }
            return dt;
        }
        
        #endregion
     
       



        #region Attachment File

        /// <summary>
        /// 图纸文件的datatable     与upProductFile 统一
        /// </summary>
        protected DataTable DtDUpFile
        {
            get
            {
                if (Session[SessionMapName] != null)
                {
                    return (DataTable)Session[SessionMapName];
                }
                else
                {
                    return CreateUpFileDT();
                }
            }
            set
            {
                Session[SessionMapName] = value;
            }
        }

        /// <summary>
        /// 技术文件的datatable
        /// </summary>
        public DataTable DtTechFile
        {
            set { Session[SessionTechName] = value; }
            get
            {
                if (Session[SessionTechName] == null)
                {
                    return CreateUpFileDT();
                }
                else
                {
                    return (DataTable)Session[SessionTechName];
                }
            }
        }

        private DataTable CreateUpFileDT()
        {
           

            return MdProduct.CreateUpFileDT();

        }
        #endregion



        static string SessionMapName = "";
        static string SessionTechName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

               

                SessionMapName = MdProduct.QuerySessionFileName("5");
                SessionTechName = MdProduct.QuerySessionFileName("6");

                Session[SessionMapName] = null;

                Session[SessionTechName] = null;

                InitEditData();
                BindDDLProductType();
               
              
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();iframeAutoFit();");
        }

        protected void btnAddMapFileHide_Click(object sender, EventArgs e)
        {
            try
            {
                BindMapFileData();
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        private void BindMapFileData()
        {
            try
            {
                foreach (DataRow dr in DtDUpFile.Rows)
                {
                    dr["FormID"] = lblProductID.Text.Trim();
                }

                grdResultMap.DataSource = DtDUpFile;
                grdResultMap.DataBind();
                UIHelper.RunScript(this.Page, "iframeAutoFit(); ");
            }
            catch { }
        }



        protected void btnAddTechFileHide_Click(object sender, EventArgs e)
        {
            try
            {
                BindTechFileData();
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        private void BindTechFileData()
        {
            foreach (DataRow dr in DtTechFile.Rows)
            {
                dr["FormID"] = lblProductID.Text.Trim();
            }
            grdResultTech.DataSource = DtTechFile;
            grdResultTech.DataBind();

            UIHelper.RunScript(this.Page, "iframeAutoFit(); ");

        }

       

        private void ChangeProductID()
        {
            //by zhang
            this.lblProductID.Text = ClsComm.GetMaxSequenceID(sequenceName + ddlProductType.SelectedValue.Trim(), ddlProductType.SelectedValue.Trim(), 4);
        }

        private void BindDDLProductType()
        {
            DataTable dt = MdProducttype.GetMdProducttypeAll().Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                this.ddlProductType.DataSource = dt;
                this.ddlProductType.DataTextField = "ProductTypeName";
                this.ddlProductType.DataValueField = "ProductTypeID";
                this.ddlProductType.DataBind();
            }

            UIHelper.InsertFirstItem(ddlProductType);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //GetGridViewData();
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写产品资料！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblProductID.Text.Trim()))
                {
                    if (!(ValidateData()))
                    {
                      
                        return;
                    }
                    MdProductEntity product = new MdProductEntity();
                    product.ProductID = this.lblProductID.Text.Trim();
                    product.ProductName = this.txtProductName.Text.Trim();
                    product.Unit = this.txtUnit.Text.Trim();
                    product.Specifications = this.txtSpecifications.Text.Trim();
                    product.ProductTypeID = this.ddlProductType.SelectedValue.Trim();
                    product.SafeStock = GetDecimal(txtSafeStock);
                    product.OutSide = GetDecimal(txtOutSide); ;
                    product.InSide = GetDecimal(txtInSide);
                    product.Status = "1";
                    product.ModifyDate = DateTime.Now;
                    product.ModifyUserID = CurrentUser.UserID;
                    product.ModifyUserName = CurrentUser.UserName;


                    List<MdAttachmentEntity> dtResultMapFile = GetDataViewFiles(product.ProductID, DtDUpFile, "ProductMap");
                    List<MdAttachmentEntity> dtResultTechFile = GetDataViewFiles(product.ProductID, DtTechFile, "ProductTech");


                    if (MdProduct.Save(product, dtResultMapFile, dtResultTechFile, false))
                    {
                        ClsComm.SetMaxSequenceID(sequenceName + ddlProductType.SelectedValue.Trim());
                        base.LogAction(BaseEnum.ActionType.Add, product.ProductID, true, null, new EntityBase[] { product });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../MasteData/ProductList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }

            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        private static List<MdAttachmentEntity> GetDataViewFiles(string strProductID, DataTable dt, string strFormType)
        {
            List<MdAttachmentEntity> lstyFile = new List<MdAttachmentEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow drItem in dt.Rows)
                {
                    MdAttachmentEntity Detailentity = new MdAttachmentEntity();
                    Detailentity.AttachmentID = Guid.NewGuid().ToString();
                    Detailentity.FileType = CommonMethod.GetString(drItem["FileType"]);
                    Detailentity.FileSize = Convert.ToInt32(drItem["FileSize"]);
                    Detailentity.UpDateTime = DateTime.Now;
                    Detailentity.FileURL = CommonMethod.GetString(drItem["FileURL"]);
                    Detailentity.FileName = CommonMethod.GetString(drItem["FileName"]);
                    Detailentity.FormType = strFormType;//"entity";
                    Detailentity.FormID = strProductID;
                    Detailentity.Status = "1";
                    lstyFile.Add(Detailentity);
                }
            }
            return lstyFile;

        }

        protected void ddlProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeProductID();
        }


        protected void btnAddhid_Click(object sender, EventArgs e)
        {
            try
            {
                BindMapFileData();

            }
            catch (Exception ex) { }

        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }


        protected void grdResultMap_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":

                    // GetGridViewData();
                    DataTable dtTemp = DtDUpFile.Copy();

                    DataRow[] drsSelect = dtTemp.Select("AttachmentID='" + strCode + "'");
                    if (drsSelect != null && drsSelect.Length > 0)
                    {
                        dtTemp.Rows.Remove(drsSelect[0]);
                        dtTemp.AcceptChanges();
                        DtDUpFile = dtTemp.Copy();
                        BindMapFileData();
                    }

                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);

                    break;

                default:
                    break;
            }
        }



        //Tech file Delete
        protected void grdResultTech_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":

                    // GetGridViewData();
                    DataTable dtTemp = DtTechFile.Copy();

                    DataRow[] drsSelect = dtTemp.Select("AttachmentID='" + strCode + "'");
                    if (drsSelect != null && drsSelect.Length > 0)
                    {
                        dtTemp.Rows.Remove(drsSelect[0]);
                        dtTemp.AcceptChanges();
                        DtTechFile = dtTemp.Copy();
                        BindTechFileData();
                    }

                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);

                    break;

                default:
                    break;
            }
        }




        #region 数据有效验证
        private bool ValidateData()
        {
            string strMention = "";




            if (string.IsNullOrEmpty(ddlProductType.SelectedValue))
            {
                strMention += "请选择产品类别！";
            }
            if (string.IsNullOrEmpty(txtProductName.Text.Trim()))
            {
                strMention += "请输入产品名称！";
            }

            MdProduct entity = new MdProduct();
            //if (entity.IsIDExists(this.lblProductID.Text.Trim()))
            //{
            //    ChangeProductID();
            //    strMention += "产品编号已存在，请重新保存！";

            //}

            if (entity.IsNameExists(this.txtProductName.Text.Trim(), this.lblProductID.Text.Trim()))
            {
                 strMention += "产品名称已存在，请重新输入！";

            }

            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }


        #endregion


     


    }
}